<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="请输入巡查员名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="编号" prop="id" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phoneNum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="巡查员名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.state | statusFilter">
            {{ row.state === true ? '启用':'禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button size="mini" type="success" @click="handleUpdate(row)">
            工作分配
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="80px" style="width: 500px; margin-left:50px;">
        <el-form-item label="区域分配" prop="localeIds">
          <div class="block">
            <el-cascader
              v-model="temp.localeIds"
              :options="options"
              :props="props"
              clearable
            />
          </div>
        </el-form-item>
        <el-form-item label="时间分配" prop="dutys">
          <el-select v-model="temp.dutys" multiple placeholder="请选择">
            <el-option
              v-for="item in duty_s"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { allocWork } from '@/api/alloction/alloction-work'
import { listDutyAll } from '@/api/info/duty'
import { listInspector, listAllocInfoByInspectorId } from '@/api/info/personnel'
import { listLocale } from '@/api/info/monitor-point'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'WorkAllocation',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        true: 'success',
        false: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      options: [],
      duty_s: [],
      props: {
        multiple: true,
        value: 'id',
        label: 'name',
        children: 'child'
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        name: ''
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: [{ key: true, text: '启用' }, { key: false, text: '禁用' }],
      showReviewer: false,
      temp: {
        localeIds: [],
        dutys: [],
        inspectorId: ''
      },
      dialogFormVisible: false,
      dialogFormVisible1: true,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加',
        distribute: '工作分配'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {},
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    this.listLocale()
    this.listDutyAll()
  },
  methods: {
    removeChildForTreeList(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].child.length < 1) {
          data[i].child = undefined
        } else {
          this.removeChildForTreeList(data[i].child)
        }
      }
      return data
    },
    listLocale() {
      this.listLoading = true
      listLocale({}).then(response => {
        const { data } = response
        this.options = this.removeChildForTreeList(data)
      })
    },
    listDutyAll() {
      this.listLoading = true
      listDutyAll({}).then(response => {
        const { data } = response
        this.duty_s = data
      })
    },
    getList() {
      this.listLoading = true
      listInspector(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        localeIds: [],
        dutys: [],
        inspectorId: ''
      }
    },
    handleUpdate(row) {
      this.rules = {
        // todo
      }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.listLoading = true
      listAllocInfoByInspectorId({ id: row.id }).then(response => {
        const { data } = response
        this.listLoading = false
        this.temp.localeIds = data.localeIds
        this.temp.dutys = data.dutys
        this.temp.inspectorId = row.id
      })
    },
    /**
     * 数组显示转换
     * @param isForward
     */
    convert(source, result) {
      for (let index = 0; index < source.length; index++) {
        console.log(result)
        if (source[index].child !== undefined) {
          result.push(source[index])
          return this.convert(source[index].child, result)
        } else {
          return this.convert(source[index], result)
        }
      }
    },
    updateData() {
      console.log('duty+++++++++', this.temp)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const param = Object.assign({}, this.temp) // copy obj
          param.localeIds = []
          this.temp.localeIds.forEach((item, index) => {
            param.localeIds.push(item[item.length - 1])
          })
          console.log('param+++++++++++', param)
          allocWork(param).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '分配成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
